<template>
  <div class="main-page">
    <PageSearch :search-form-config="searchFormConfig" :form-data.sync="formData" @searchBtnClick="handleSearch" />
    <el-row type="flex" justify="end">
      <el-button type="primary" icon="el-icon-plus" size="medium" @click="addDeviceToGroup">
        添加分组
      </el-button>
    </el-row>
    <PageContent ref="pageContent" :form-data="formData" :content-table-config="contentConfig" @selectionChange="selectionChange">
      <template #image="scope">
        <el-image v-if="scope.row.picture" style="width: 60px; height: 60px" :src="getPicUrl(scope.row.picture)" :preview-src-list="getPicUrlList(scope.row.picture)">
        </el-image>
        <span v-else>无</span>
      </template>

      <template #onlineCode="{ row }">
        {{
          row.onlineCode == 1
            ? "离线"
            : row.onlineCode == 0
              ? "在线":"未知"
        }}
      </template>
      <template #onUse="{ row }">
        {{
          row.onUse == true
            ? "已安装"
            : row.onUse == false
              ? "未安装":"未知"
        }}
      </template>
      <template #operate="{ row }">
        <el-button type="text" size="small" icon="el-icon-plus" @click="addGroupRow(row)">
          添加分组
        </el-button>
        <el-button type="text" size="small" icon="el-icon-money" @click="handleViewIncome(row)">
          收益
        </el-button>
        <el-button type="text" size="small" icon="el-icon-search" @click="handleDeviceRealTimeInfo(row)">
          实时信息
        </el-button>
        <el-button type="text" size="small" icon="el-icon-close" @click="cancelGroupRow(row)">
          取消分组
        </el-button>
      </template>
    </PageContent>
    <!-- 设备实时信息 -->
    <device-info v-if="showDeviceInfo" :show.sync="showDeviceInfo" :sn="sn"></device-info>
    <!-- 收益明细 -->
    <device-income v-if="showIncome" :show.sync="showIncome" :sn="sn"></device-income>

    <el-dialog title="添加分组" :visible.sync="showAddGroup" width="50%" :before-close="showAddGroupClose">
      <el-form :model="dialogFormData">
        <el-form-item>
          添加<span v-for="item in selectionList" :key="item.id">&lt;{{ item.name }}&gt; </span>到分组
          <el-select v-model="dialogFormData.deviceIdList" clearable placeholder="请选择分组" filterable remote :remote-method="remoteMethod" :loading="selectLoading" @visible-change="onSelectChange">
            <el-option v-for="item in groupOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addGroup">
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import dialogMixin from "@/mixins/dialogMixin";
import { contentConfig } from "./config/content.config";
import { searchFormConfig } from "./config/search.config";
import { menus } from "@/config/enum";
import DeviceInfo from "./deviceInfo.vue";
import DeviceIncome from "./deviceIncome.vue";
import request from "@/utils/request";
export default {
  name: "DeviceList",
  components: {
    DeviceInfo,
    DeviceIncome,
  },
  mixins: [dialogMixin],
  data() {
    return {
      exportLoading: false,
      brandIdOptions: [],
      modalDownLoadData: {
        brandId: "",
      },
      modalDownLoadRules: {
        brandId: [{ required: true, message: "请选择品牌", trigger: "blur" }],
      },
      exportDialogVisible: false,
      showIncome: false,
      deviceList: [
        {
          label: "已绑设备总数",
          key: "total",
          icon: require("../deviceList/images/icon-total.png"),
        },
        {
          label: "在线设备数",
          key: "online",
          icon: require("../deviceList/images/icon-online.png"),
        },
        {
          label: "离线设备数",
          key: "offline",
          icon: require("../deviceList/images/icon-offline.png"),
        },
      ],
      fileList: [],
      sn: "",
      title: "新建设备",
      menus,
      contentConfig,
      searchFormConfig,
      btnLoading: false,
      confirmBtnLoading: false,
      dialogVisible: false,
      showDeviceInfo: false,
      formData: {}, // 搜索表单数据
      modalFormData: {
        sn: "",
        name: "",
        brandId: "",
        picture: "",
      }, // 模态框表单数据
      selectionList: [],
      showAddGroup: false,
      dialogFormData: {},
      groupOption: [],
      selectLoading: false,
      defaultOptionArr:[],
    };
  },
  computed: {
    getPicUrl() {
      return (data) => {
        return JSON.parse(data)[0]?.absolutePath;
      };
    },
    getPicUrlList() {
      return (data) => {
        const arr = JSON.parse(data);
        if (Array.isArray(arr)) {
          return arr.map((item) => item.absolutePath);
        }
      };
    },
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.fileList = [];
      }
    },
  },
  mounted() {
    this.getGroup();
  },
  methods: {
    onSelectChange(visible){
      if(!visible){
        this.groupOption = this.defaultOptionArr;
      }
    },
    remoteMethod(query) {
      let that = this;
      that.selectLoading = true;
      request({
        url: `/device/group/myGroup`,
        method: "get",
        params: {
          pageNum: 1,
          pageSize: 100,
          groupName: query
        },
      }).then((res) => {
        if (res.code === 200) {
          that.groupOption = res.data.records;
        }
        that.selectLoading = false;
      }).catch((err) => {
        console.log(err);
        that.selectLoading = false;
      })
    },
    cancelGroupRow(row) {
      let that = this;
      this.$confirm(`是否确认取消${row.name}的分组`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/device/group/cancelGroup`,
          method: "post",
          data: {
            "groupId": row.groupId,
            "deviceIdList": [row.id]
          }
        }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '取消成功!'
            });
            that.handleSearch();
          }
        }).catch((err) => {
          console.log(err);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addGroupRow(row) {
      this.selectionList.push(row);
      this.addDeviceToGroup()
    },
    addGroup() {
      let that = this;
      let arrId = [];
      for (let i = 0; i < that.selectionList.length; i++) {
        arrId.push(that.selectionList[i].id)
      }
      request({
        url: `/device/group/moveToGroup`,
        method: "post",
        data: {
          "groupId": this.dialogFormData.deviceIdList,
          "deviceIdList": arrId
        },
      }).then((res) => {
        if (res.code === 200) {
          that.showAddGroupClose();
          that.handleSearch();
          this.$message.success('添加成功')
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    addDeviceToGroup() {
      if (this.selectionList.length === 0) {
        this.$message.error('请选择设备');
        return
      }
      this.showAddGroup = true;
      this.groupOption = this.defaultOptionArr;
    },
    getGroup() {
      let that = this;
      request({
        url: `/device/group/myGroup`,
        method: "get",
        params: {
          pageNum: 1,
          pageSize: 100
        },
      }).then((res) => {
        if (res.code === 200) {
          that.defaultOptionArr = res.data.records;
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    showAddGroupClose() {
      this.selectionList = [];
      this.showAddGroup = false;
      this.dialogFormData = {};
    },
    selectionChange(selection) {
      this.selectionList = selection;
      console.log(this.selectionList)
    },
    handleSearch() {
      let onlineStatus = this.formData.onlineStatus;
      let onlineCode = "";
      if (onlineStatus != "0" && onlineStatus != "") {
        onlineCode = onlineStatus - 1;
      }
      this.formData.onlineStatus = "";
      this.formData.onlineCode = onlineCode;

      this.$refs.pageContent.queryTblMain();
    },
    handleDeviceRealTimeInfo({ sn }) {
      this.sn = sn;
      this.showDeviceInfo = true;
    },
    handleViewIncome({ sn }) {
      this.sn = sn;
      this.showIncome = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.device-static {
  padding: 0 20px;
  margin-top: 20px;
  .icon-point {
    margin-right: 5px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: inline-block;
    position: relative;
    top: -2px;
    &.icon-point-online {
      background-color: #67c23a;
    }
    &.icon-point-offline {
      background-color: #f56c6c;
    }
  }
}
.name {
  text-align: center;
}
.info {
  margin-top: 10px;
  display: flex;
  align-items: center;
  font-size: 30px;
  color: #1d2129;
  text-align: center;
  justify-content: center;
  img {
    margin-right: 8px;
  }
  .unit {
    display: inline-block;
    margin: 6px 0 0 4px;
    font-size: 16px;
  }
}
::v-deep {
  .el-upload-list {
    display: none;
  }
  .el-upload-list__item-name {
    display: none;
  }
}
</style>
